import { Inject, Injectable, Logger, Scope } from '@nestjs/common';
import { Request } from 'express';
import { REQUEST } from '@nestjs/core';
import { ConfigService } from '@nestjs/config';

import {
  AuthTokenResponsePassword,
  createClient,
  SupabaseClient,
} from '@supabase/supabase-js';

// import { ExtractJwt } from 'passport-jwt';

@Injectable({ scope: Scope.REQUEST })
export class SupabaseService {
  private readonly logger = new Logger(SupabaseService.name);
  private clientInstance: SupabaseClient;

  constructor(
    @Inject(REQUEST) private readonly request: Request,
    private readonly configService: ConfigService,
  ) {}

  getClient() {
    this.logger.log('getting supabase client...');
    return new Promise<SupabaseClient>((resolve, reject) => {
      if (this.clientInstance) {
        this.logger.log('client exists - returning for current Scope.REQUEST');
        resolve(this.clientInstance);
      }

      this.logger.log('initialising new supabase client for new Scope.REQUEST');

      this.clientInstance = createClient(
        this.configService.get('SUPABASE_URL'),
        this.configService.get('SUPABASE_KEY'),
        {
          auth: {
            autoRefreshToken: true,
            detectSessionInUrl: false,
          },
        },
      );
      // const token = ExtractJwt.fromAuthHeaderAsBearerToken()(this.request);
      try {
        // const session = JSON.parse(token);
        // this.clientInstance.auth.setSession(session);
        this.logger.log('auth has been set!');

        resolve(this.clientInstance);
      } catch (error) {
        reject(error);
      }
    });
  }

  getTestToken() {
    return new Promise((resolve, reject) => {
      this.clientInstance = createClient(
        this.configService.get('SUPABASE_URL'),
        this.configService.get('SUPABASE_KEY'),
        {
          auth: {
            autoRefreshToken: true,
            detectSessionInUrl: false,
          },
        },
      );
      this.clientInstance.functions
        .invoke('create_user_on_signup', {
          body: {
            user_id: '00000000-0000-0000-0000-000000000000',
            user_exists: false,
          },
        })
        .then(() => {
          this.clientInstance.auth
            .signInWithPassword({
              email: '15927027721@163.com',
              password: 'j.haha512',
            })
            .then((data: AuthTokenResponsePassword) => {
              // console.log(data);
              resolve(data);
            })
            .catch((error) => {
              reject(error);
            });
        });
    });
  }

  signOut() {
    return new Promise((resolve, reject) => {
      this.getClient().then((client) => {
        client.auth
          .signOut()
          .then((err) => {
            console.log(err);
            if (err.error) {
              reject(err);
            } else {
              resolve(true);
            }
            resolve(true);
          })
          .catch((error) => {
            reject(error);
          });
      });
    });
  }
}
